#include "mprpcchannel.h"
#include <string>
#include "mprpcapplication.h"
#include "rpcheader.pb.h"
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <netinet/in.h>
#include "mprpccontroller.h"
#include "zookeeperutil.h"
/*
header_size +service_name+method_name+ args_size args
*/
void MpRpcChannel::CallMethod(const google::protobuf::MethodDescriptor *method,
                              google::protobuf::RpcController *controller, const google::protobuf::Message *request,
                              google::protobuf::Message *response, google::protobuf::Closure *done)
{
    const google::protobuf::ServiceDescriptor *sd = method->service();
    std::string service_name = sd->name();
    std::string method_name = method->name();

    // 获取参数的序列化的长度的字符串长度 args_size
    uint32_t args_size = 0;
    std::string args_str;
    if (request->SerializeToString(&args_str))
    {
        args_size = args_str.size();
    }
    else
    {
        // std::cout << "Serialize request error!" << std::endl;
        controller->SetFailed("Serialize request error!");
        return;
    }

    // 定义rpc请求的header
    mprpc::RpcHeader rpcheader;
    rpcheader.set_service_name(service_name);
    rpcheader.set_method_name(method_name);
    rpcheader.set_args_size(args_size);

    uint32_t header_size = 0;
    std::string header_str;
    if (rpcheader.SerializeToString(&header_str))
    {
        header_size = header_str.size();
    }
    else
    {
        // std::cout << "Serialize rpcheader error!" << std::endl;
        controller->SetFailed("Serialize rpcheader error!");
        return;
    }
    // 组织发送的数据
    std::string send_rcp_str;
    // 这个方法了解一下 很重要
    send_rcp_str.insert(0, std::string((char *)&header_size, 4));
    send_rcp_str += header_str;
    send_rcp_str += args_str;

    // 打印调试信息
    std::cout << "=========================================================================" << std::endl;
    std::cout << "header_size:" << header_size << std::endl;
    std::cout << "rpc_header_str:" << header_str << std::endl; // UserServiceRpRegister
    std::cout << "service_name:" << service_name << std::endl;
    std::cout << "method_name:" << method_name << std::endl;
    // std::cout << "args_size:" << args_size << std::endl;
    std::cout << "arg_str:" << args_str << std::endl;
    std::cout << "=========================================================================" << std::endl;

    // 使用tcp变成

    int clientfd = socket(AF_INET, SOCK_STREAM, 0);

    if (-1 == clientfd)
    {
        char err_buf[1024] = {0};
        sprintf(err_buf, "create socket error! errno:%d", errno);
        controller->SetFailed(err_buf);
        close(clientfd);
        return;
    }
    // std::string ip = MprpcApplication::GetInstance()->GetConfig().Load("rpcserverip");
    // uint16_t port = atoi(MprpcApplication::GetInstance()->GetConfig().Load("rpcserverport").c_str());

    ZkClient ZkClient;
    ZkClient.Start();
    // a按照zookeeper的路径获取ip和端口
    std::string method_path = "/" + service_name + "/" + method_name;
    std::string host_data = ZkClient.GetData(method_path.c_str());

    if (host_data == "")
    {
        controller->SetFailed(method_path);
        return;
    }

    int idx = host_data.find(":");
    if (idx == -1)
    {
        controller->SetFailed(method_path + "address is invalid!");
        return;
    }
    std::string ip = host_data.substr(0, idx);
    uint16_t port = atoi(host_data.substr(idx + 1, host_data.size() - idx).c_str());

    struct sockaddr_in serveraddr;
    serveraddr.sin_family = AF_INET;
    serveraddr.sin_port = htons(port);
    serveraddr.sin_addr.s_addr = inet_addr(ip.c_str());

    // 发起连接
    if (-1 == connect(clientfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr)))
    {
        close(clientfd);
        char err_buf[1024] = {0};
        sprintf(err_buf, "connect socket error! errno:%d", errno);
        controller->SetFailed(err_buf);
        return;
    }

    std::cout << "connect SUCCESS!" << std::endl;

    if (-1 == send(clientfd, send_rcp_str.c_str(), send_rcp_str.size(), 0))
    {
        close(clientfd);
        char err_buf[1024] = {0};
        sprintf(err_buf, "send socket error! errno:%d", errno);
        controller->SetFailed(err_buf);
        return;
    }
    std::cout << "SEND SUCCESS!" << std::endl;

    // 接受rpc请求的响应
    char buf[1024] = {0};
    int recv_size = 0;
    if (-1 == (recv_size = recv(clientfd, buf, sizeof(buf), 0)))
    {
        close(clientfd);
        char err_buf[1024] = {0};
        sprintf(err_buf, "recv socket error! errno:%d", errno);
        controller->SetFailed(err_buf);
        return;
    }
    // 反序列化rpc调用的响应数据
    // std::string response_Str(buf,0,recv_size);
    // std::cout<<"recv_size:"<<recv_size<<std::endl;
    // std::cout<<"response_Str:"<<response_Str<<std::endl;
    // 这里要明白哦 这样做的原因
    if (response->ParseFromArray(buf, recv_size))
    {
        std::cout << "parse response success!" << std::endl;
    }
    else
    {
        close(clientfd);
        char err_buf[512] = {0};
        snprintf(err_buf, sizeof(err_buf), "parse response error! errno:%s", buf);
        controller->SetFailed(err_buf);
        return;
    }
    close(clientfd);
    return;
}